package com.sgcc.pda.web;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;


import com.sgcc.pda.tools.LogPrintUtils;

/**
 * @创建者：suven on 2020/3/24 10:59
 * @描述：网络AIDL绑定
 * @版本：1.0
 * @修改人：
 * @修改时间：
 * @修改说明：
 * @修改版本：
 */
public class WebManager {

    private static final String PACKAGE_NAME = "com.sgcc.pda.web";
    private static final String CLASS_NAME = "com.sgcc.pda.web.AIDL_WEB_SERVICE";


    private static WebManager mInstance;
    private IWebManager mWebManager = null;
    private boolean bindflag = false;//绑定标志
    private IWebBindServiceCallBack serviceCallBack;

    interface IWebBindServiceCallBack {
        void onSuccess();
    }

    /**
     * 单例
     *
     * @return
     */
    public static synchronized WebManager getInstance() {
        if (mInstance == null) {
            mInstance = new WebManager();
        }
        return mInstance;
    }

    public IWebManager getWebManager() {
        return mWebManager;
    }

    public boolean isBind() {
        return bindflag;
    }
    private boolean bind(Context context, IWebBindServiceCallBack serviceCallBack) {
        //如果没有绑定 则先进行aidl服务绑定
        this.serviceCallBack = serviceCallBack;
        if (!bindflag) {
            //注册AIDL
            Intent intent = new Intent(CLASS_NAME);
            intent.setPackage(PACKAGE_NAME);
            try {
                bindflag = context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
            } catch (SecurityException e) {
                e.printStackTrace();
                LogPrintUtils.d("IWebManager-绑定异常 ", e);
            }
        }
        return bindflag;
    }

    public boolean bind(Context context) {
        return bind(context, null);
    }

    /**
     * 取消aidl绑定
     *
     * @param context
     */
    public void unBind(Context context) {
        if (bindflag) context.unbindService(conn);
    }

    /**
     * 实例化aidl连接服务
     */
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogPrintUtils.d("绑定成功-IWebManager");
            bindflag = true;
            mWebManager = IWebManager.Stub.asInterface(service);
            if (serviceCallBack != null) {
                serviceCallBack.onSuccess();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogPrintUtils.d("解绑成功-IWebManager");
            mWebManager = null;
            bindflag = false;
        }
    };
}
